﻿using System;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using Microsoft.Practices.ServiceLocation;
using Microsoft.Practices.Unity;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using SkeletonNET.Crud.KeyCache;
using SkeletonNET.Crud.Repository;
using SkeletonNET.Base.Crud.UnitOfWork;

namespace SkeletonNET.Data.Tests
{
    [TestClass]
    public class EntityKeyTests
    {
        [TestInitialize]
        public void Test()
        {
            var container = new UnityContainer();
            ServiceLocator.SetLocatorProvider(() => new UnityServiceLocator(container));

            // Setup repository
            container.RegisterType(typeof(IRepository<>), typeof(Repository<>));
            // Setup the keycache
            container.RegisterType<IEntityKeyCache, EntityKeyCache>();
            // Setup th fake unitofwork
            container.RegisterType<IUnitOfWork, FakeDbContext>();
        }

        [TestMethod]
        public void TestEntityKey()
        {
            var keyCache = ServiceLocator.Current.GetInstance<IEntityKeyCache>();
            var keyValue = keyCache.GetKeyValue(new TestEntity() { ID = 100 });
            Assert.IsTrue((int)keyValue == 100);
        }

        [TestMethod]
        public void TestGetKeyName()
        {
            var keyCache = ServiceLocator.Current.GetInstance<IEntityKeyCache>();
            var propName = keyCache.GetKeyName(typeof(TestEntity));
            Assert.IsTrue(propName == "ID");
        }

        [TestMethod]
        public void TestKeyExpression()
        {
            // Get a TestEntity repository
            var repo = ServiceLocator.Current.GetInstance<IRepository<TestEntity>>();
            var keyCache = ServiceLocator.Current.GetInstance<IEntityKeyCache>();

            for (int i = 0; i < 10; i++)
                repo.Insert(new TestEntity() { ID = i });

            // Query the TestEntity repo for the entity with value 5
            var lookup = repo.GetQuery().Where(keyCache.GetExpression<TestEntity>(5));

            // Verify that there is only 1 value in the repo
            Assert.IsTrue(lookup.Count() == 1);
        }
    }
}
